const db=require('../utils/db')
const util=require('../utils/util.js')
const jsonToken=require("jsonwebtoken")
const koaJwt=require("koa-jwt");
const secret = 'jwt_secret'//koa-jwt中间件
// import { responseClient} from '../utils/util.js'
// router.prefix('/users')

// router.get('/', async function (ctx, next) {
//   // ctx.body = 'this is a users response!'
//   let data =await new Promise((resolve, reject)=>{
//     let sqlLang = `select * from user`;
//     db.query(sqlLang, (err, data)=>{
//       if(err) reject(err);
//       resolve(data);	// 返回拿到的数据
//     })
//   })
//   ctx.body=data
// })

// router.get('/bar', function (ctx, next) {
//   ctx.body = 'this is a users/bar response'
// })

//登录
exports.login=async (ctx) =>{
  // ctx.body="login"
  let { email, password } = ctx.request.body
  // console.log("登录参数",ctx.request.body)
  if (!email) {
    util.responseClient(ctx, 400, 2, '用户邮箱不可为空');
    return;
  }
  if (!password) {
    util.responseClient(ctx, 400, 2, '密码不可为空');
    return;
  }
// 验证用户是否已经在数据库中
let res=await new Promise((resolve, reject)=>{
  let sqlLang = `select * from user where email='${email}' and password='${password}'`;
  return db.query(sqlLang, (err, data)=>{
    if (err) throw err;
    if (data.length > 0) {
      resolve(data);
    } else {
      resolve(false)
    }  
  })    
})
if(res){
   //生成token
   let token=jsonToken.sign({ email:email, password:password },secret,{expiresIn: 3600})
  let userInfo={
    _id:res[0].id,
    avatar:res[0].avatar,
    name:res[0].name,
    token:token
  }
   util.responseClient(ctx, 200, 0, '登录成功！',userInfo)  
}else{
   util.responseClient(ctx, 200, 1, '用户名或者密码错误!')
}
}


//注册
exports.register =async (ctx) => {
  let { name, password, phone, email, introduce, type } = ctx.request.body
  console.log('请求参数',ctx.request.body);
  if (!email) {
    util.responseClient(ctx, 400, 2, '用户邮箱不可为空');
    return;
  }
  const reg = new RegExp(
    '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$',
  ); //正则表达式
  if (!reg.test(email)) {
    util.responseClient(ctx, 400, 2, '请输入格式正确的邮箱！');
    return;
  }
  if (!name) {
    util.responseClient(ctx, 400, 2, '用户名不可为空');
    return;
  }
  if (!password) {
    util.responseClient(ctx, 400, 2, '密码不可为空');
    return;
  }
    // 验证用户是否已经在数据库中
    let res=await new Promise((resolve, reject)=>{
        let sqlLang = `select * from user where email='${email}'`;
      return  db.query(sqlLang, (err, data)=>{
          if (err) throw err;
          if (data.length > 0) {
            resolve(data)          
          } else {
            resolve(false);
          }
        })    
      })
    
     if(res){
      util.responseClient(ctx, 200, 1, '用户邮箱已存在！')
      return;
     }
      // 找不到对应的账号，直接插入一个
    //   //生成token
    //  let token=jsonToken.sign({ name:name, password:password },secret,{expiresIn: 3600})
		let newAccount= await new Promise((resolve, reject) => {
			// 生成token name, password, phone, email, introduce, type
			// const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 })
			return db.query(`insert into user (email,password,name,phone,introduce) values ('${email}', '${password}', '${name}', '${phone}', '${introduce}')`, (error, data) => {
				if (error) throw error;
				// 已插入数据，
        resolve(data)
			})
		})
    console.log(newAccount)
   if(newAccount){
    let userInfo={
      _id:newAccount.insertId,
      avatar:newAccount.avatar,//头像后面在前端上传
      name:name,
    }
    util.responseClient(ctx, 200, 0, '注册成功', userInfo);
   }
}


exports.logout=async (ctx) => {

}